package com.zyc.ui;

import com.zyc.R;
import com.zyc.misc.AudioUtil;
import com.zyc.misc.Constant;

import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ToggleButton;

import java.util.Observable;
import java.util.Observer;

/**
 * @author ZengYongchang@gmail.com
 */
public class AudioRecordActivity extends Activity implements Observer {
    private ToggleButton mBtnToggleRecordAudio;
    private ListView mListView;

    private Uri mNewUri;
    private String mNewAudioFilePath;
    private DbContentObserver mDbContentObserver;

    private AudioUtil mAudioUtil;
    private Handler mHandler = new Handler();

    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.audio_record_activity);
        
        mBtnToggleRecordAudio = (ToggleButton) this.findViewById(R.id.btn_toggle_recording);
        mBtnToggleRecordAudio.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnToggleRecordAudioOnClickImpl();
            }
        });
        mListView = (ListView) findViewById(R.id.recorded_audio_file_list_view);
        mListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapter, View view, int position, long rowId) {
                listViewOnItemClickImpl(rowId);
            }
        });

        mAudioUtil = new AudioUtil();
        // Use ContentObserver to listen database's change. If some data added, in this file's onChange() function, refresh this activity's list view. 
        // Relevant function: in LocalContentProvider.java's query() function, see setNotificationUri(), and in update() function, see notifyChange(). 
        mDbContentObserver = new DbContentObserver(new Handler());
        getContentResolver().registerContentObserver(Constant.Db.CONTENT_URI, true, mDbContentObserver);
        refreshListView();
    }


    private void refreshListView() {
        Cursor cursor = managedQuery(Constant.Db.CONTENT_URI, new String[] {
                Constant.Db._ID, 
                Constant.Db.START_RECORDING_TIME_COLUMN,
                Constant.Db.STOP_RECORDING_TIME_COLUMN,
                Constant.Db.EXPIRE_TIME_COLUMN, 
                Constant.Db.PRIORITY_COLUMN,
                Constant.Db.AUDIO_FILE_PATH_COLUMN
        }, Constant.Db.IS_EXECUTED_COLUMN +" is null", null, "_id desc");
        RemindItemCursorAdapter remindItemCursorAdapter = new RemindItemCursorAdapter(this, cursor);
        mListView.setAdapter(remindItemCursorAdapter);
    }


    @Override
    public void update(Observable observable, Object data) {
        mBtnToggleRecordAudio.setChecked(!mBtnToggleRecordAudio.isChecked());
        switchToStopButton();
    }


    public void switchToStopButton() {
        mAudioUtil.stopRecordingAudio();
        ContentValues values = new ContentValues();
        values.put(Constant.Db.STOP_RECORDING_TIME_COLUMN, System.currentTimeMillis());
        values.put(Constant.Db.AUDIO_FILE_PATH_COLUMN, mNewAudioFilePath);
        getContentResolver().update(mNewUri, values, null, null);
    }


    private void btnToggleRecordAudioOnClickImpl() {
        if (mBtnToggleRecordAudio.isChecked()) {
            ContentValues values = new ContentValues();
            values.put(Constant.Db.START_RECORDING_TIME_COLUMN, System.currentTimeMillis());
            mNewUri = getContentResolver().insert(Constant.Db.CONTENT_URI, values);
            String newAudioFileName = mNewUri.getPathSegments().get(1) + Constant.AUDIO_FILE_POSTFIX;
            mAudioUtil.startRecordingAudio(this, newAudioFileName);
            mNewAudioFilePath = getFileStreamPath(newAudioFileName).getAbsolutePath();
            mHandler.postDelayed(runnable, Constant.RECORD_LENGTH_LIMIT_IN_MILLISECOND);
        } else {
        	mHandler.removeCallbacks(runnable);
            switchToStopButton();
        }
    }
    
    
    private Runnable runnable = new Runnable() {
		@Override
		public void run() {
			mBtnToggleRecordAudio.setChecked(!mBtnToggleRecordAudio.isChecked());
			switchToStopButton();
		}
	};


    private void listViewOnItemClickImpl(long rowId) {
        Intent intent = new Intent(AudioRecordActivity.this, ItemSetAndLaunchActivity.class);
        intent.setData(ContentUris.withAppendedId(Constant.Db.CONTENT_URI, rowId));
        startActivity(intent);
    }


/**
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(Constant.MENU_ITEM_SETTING).setEnabled(true);
        return super.onPrepareOptionsMenu(menu);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(Menu.NONE, Constant.MENU_ITEM_SETTING, Menu.NONE, R.string.menu_setting_item);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case Constant.MENU_ITEM_SETTING:
                startActivity(new Intent(this, SettingActivity.class));
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
**/

    
    private class DbContentObserver extends ContentObserver {
        public DbContentObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            refreshListView();
        }
    }
}
